/* global shoproot */

/**
 * Desc
 * @description Holp You Do Good But Not Evil
 * @copyright   Copyright 2014-2015 <ycchen@iwshop.cn>
 * @license     LGPL (http://www.gnu.org/licenses/lgpl.html)
 * @author      Chenyong Cai <ycchen@iwshop.cn>
 * @package     Wshop
 * @link        http://www.iwshop.cn
 */
var pdCatimg = false;
var pdImages = ['', '', '', '', ''];
var pdId = false;
var pdImageWidth = false;
var entDiscount = [];
var entDisLastOpt;

requirejs(['util', 'fancyBox', 'datatables', 'ztree', 'ztree_loader', 'ueditor', 'jUploader'], function (util, fancyBox, dataTables, ztree, treeLoader, ueditor, jUploader) {
    $(function () {

        loadingLock = false;

        fnFancyBox('#catimgPv');
        fnFancyBox('.pd-image-view');

        pdCatimg = $('#pd-catimg').val() === '' ? false : $('#pd-catimg').val();

        if ($('#mod').val() === 'edit') {
            // 编辑模式 存入图片列表
            $('.pd-images').each(function (i, node) {
                if ($(node).val() && $(node).val() !== '' && i < 5) {
                    pdImages[$(node).attr('data-sort')] = $(node).val();
                    $('.pd-image-sec').eq(parseInt($(node).attr('data-sort')) + 1).append('<img src="' + shoproot + 'uploads/product_hpic/' + $(node).val() + '" width="' + pdImageWidth + 'px" /><a href="' + shoproot + 'uploads/product_hpic/' + $(node).val() + '" class="pd-image-view"> </a><i data-id=' + $(node).attr('data-sort') + ' class="pd-image-delete"> </i>').addClass('ove');
                }
            });
            fnPdimageDelete();
            pdId = parseInt($('#pid').val());
            fnFancyBox('.pd-image-view');
        } else {
            pdId = false;
        }

        var pdCatSelect = $("#pd-catselect").find("option[value='" + $('#pd-form-cat').val() + "']");
        
        if(pdCatSelect.get(0) !== undefined){
            pdCatSelect.get(0).selected = true;
        }

        $('#pd-prom').on('change', function () {
            if (parseInt($(this).val()) === 1) {
                $('#prom_option').removeClass('hidden');
            } else {
                $('#prom_option').addClass('hidden');
            }
        });

        // 集团折扣
        $('.product-ent-discount').each(function (i, node) {
            if (i === 0) {
                $('#pd-ent-discount').val(parseFloat($(this).attr('data-discount')));
                entDisLastOpt = $(this);
            }
            entDiscount.push({
                ent: parseInt($(this).val()),
                discount: parseFloat($(this).attr('data-discount'))
            });
        });

        $('#pd-entprise').on('change', function () {
            $.each(entDiscount, function (i, n) {
                if (n.ent === parseInt(entDisLastOpt.val())) {
                    n.discount = parseFloat($('#pd-ent-discount').val());
                }
            });
            entDisLastOpt = $(this).find("option:selected");
            $.each(entDiscount, function (i, n) {
                if (n.ent === parseInt(entDisLastOpt.val())) {
                    $('#pd-ent-discount').val(n.discount);
                }
            });
        });

        $('.pd-image-sec').each(function () {
            var btn = this;
            $(this).height($(this).width());
            $.jUploader({
                button: $(btn),
                action: shoproot + '?/vProduct/ImageUpload',
                onComplete: function (fileName, response) {
                    var Btn = $(this.button[0]);
                    var R = response;
                    if (R.s > 0) {
                        var iid = parseInt(Btn.attr('data-id'));
                        var src = R.link;
                        Btn.addClass('ove').removeClass('hover');
                        util.Alert('图片上传成功');
                        if (Btn.find('img').length > 0) {
                            Btn.find('img').attr('src', src);
                            Btn.find('.pd-image-view').attr('href', src);
                        } else {
                            Btn.append('<img src="' + src + '" /><a href="' + src + '" class="pd-image-view"> </a><i data-id=' + (iid - 1) + ' class="pd-image-delete"> </i>');
                        }
                        // 商品首图
                        if (!pdCatimg || iid === 0) {
                            pdCatimg = 'product_hpic2__' + R.imgn;
                            $('#pd-catimg').val(pdCatimg);
                            $('#catimgPv').attr('href', shoproot + 'uploads/product_hpic_tmp/' + R.imgn);
                        }
                        if (iid !== 0) {
                            pdImages[iid - 1] = 'product_hpic2__' + R.imgn;
                        }
                        fnFancyBox('.pd-image-view');
                        fnPdimageDelete();
                    } else {
                        util.Alert('上传图片失败，请联系技术支持');
                    }
                }
            });
            $(this).hover(function () {
                if (!$(this).hasClass('ove')) {
                    $(this).addClass('hover');
                }
            }, function () {
                if (!$(this).hasClass('ove')) {
                    $(this).removeClass('hover');
                }
            });
        });

        // 产品首图
        if (pdCatimg) {
            $('.pd-image-sec').eq(0).addClass('ove').append('<img src="' + shoproot + 'uploads/product_hpic/' + pdCatimg + '" />');
            $('#catimgPv').attr('href', shoproot + 'uploads/product_hpic/' + pdCatimg);
        }

        $('body').css('overflow-x', 'hidden');

        uep = UM.getEditor('ueditorp', {
            autoHeight: true
        });
        uep.ready(function () {
            ueploaded = true;
        });

        // 图片已经上传过了。
        $('#save_product_btn').unbind('click').click(__ProductAlterFinish);
    });

    // 删除图片--
    function fnPdimageDelete() {
        $('.pd-image-delete').unbind('click').on('click', function () {
            var nP = $(this).parent();
            pdImages[parseInt($(this).attr('data-id'))] = '';
            nP.removeClass('ove').find('i,img').remove();
        });
    }

    /**
     * 商品编辑结束
     * @returns {undefined}
     */
    function __ProductAlterFinish() {
        if (!loadingLock) {
            // discount
            entDisLastOpt = $('#pd-entprise').find("option:selected");
            $.each(entDiscount, function (i, n) {
                if (n.ent === parseInt(entDisLastOpt.val())) {
                    n.discount = parseFloat($('#pd-ent-discount').val());
                }
            });
            var postData = $('#pd-baseinfo').serializeArray();
            var price = parseFloat($('#pd-form-prices').val());
            var discount = $('#pd-form-discount').val();
            if ($('#pd-form-title').val() !== '' && price !== '' && discount !== '') {
                var node = $(this);
                //loadingLock = true;
                node.html('数据处理中');
                // [HttpPost]
                $.post(shoproot + '?/WdminAjax/updateProduct', {
                    product_id: !pdId ? 0 : pdId,
                    product_infos: postData,
                    product_prices: price > 0 ? price : 0,
                    product_discount: discount,
                    product_images: pdImages,
                    entDiscount: entDiscount,
                    spec: getSpecs()
                }, function (r) {
                    if (r === '1') {
                        loadingLock = false;
                        if (!pdId) {
                            util.Alert('添加成功', false, function () {
                                history.go(-1);
                            });
                        } else {
                            util.Alert('保存成功');
                        }
                    } else {
                        util.Alert('保存失败');
                    }
                    node.html('保存');
                });
            } else {
                util.Alert('无法提交，表单不完整。');
            }
        } else {

        }
    }

    /**
     * 商品删除监听
     */
    util.pdDeleteListen();

    /**
     * window resize 监听
     */
    util.onresize(function () {
        $('.pd-image-sec').each(function () {
            pdImageWidth = $(this).width();
            $(this).height(pdImageWidth);
        });
    });

    /**
     * 商品规格选择，生成价格表
     * @returns {undefined}
     */
    fnFancyBox('#pd-spec-edit-btn', function () {
        DataTableMuli = true;
        $('.fancybox-skin').css('padding', '0');
        util.dataTableLis(".dTableX", true);
        $('.pd-spec-ajax-ul li a').on('click', function () {
            $('.spec-list-sp').removeClass('hover');
            $(this).addClass('hover');
            $('.spec-det-list').addClass('hidden');
            $('#spec-det-list-' + $(this).parent().attr('data-id')).removeClass('hidden');
        });
        // 确认选择
        $('#confirm_spec_btn').on('click', function () {
            var offset = 0;
            var offsetX = [];
            var specs = [];
            specs.length = 0;
            $('.pd-spec-checks:checked').each(function (i, node) {
                var dataSpid = parseInt($(this).attr('data-spid'));
                if ($.inArray(dataSpid, offsetX) === -1) {
                    offset = offsetX.push(dataSpid) - 1;
                }
                if (specs[offset] === undefined) {
                    specs[offset] = {
                        id: $(this).attr('data-spid'),
                        name: $('#spec-item-' + $(this).attr('data-spid')).html(),
                        data: []
                    };
                }
                specs[offset].data.push({
                    id: $(this).attr('data-id'),
                    name: $(this).attr('data-name')
                });
            });
            fnGenerateSpecTable(specs);
            $.fancybox.close();
        });
    });

    /**
     * 生成价格表
     * @param {type} specs
     * @returns {undefined}
     */
    function fnGenerateSpecTable(specs) {
        var thead = '<thead><tr>';
        var tbody = '<tbody>';
        var prices = parseFloat($('#pd-form-prices').val());
        // 遍历价格表
        for (var i in specs) {
            if (parseInt(i) === 0) {
                // 第二维下标
                var nex = i + 1;
                // 遍历第一维
                for (var j in specs[i].data) {
                    // 如果第二维存在
                    if (specs[nex] !== undefined) {
                        // 遍历第二维
                        for (var j1 in specs[nex].data) {
                            tbody += '<tr><td>' + specs[i].data[j].name + '</td>';
                            tbody += '<td>' + specs[nex].data[j1].name + '</td>';
                            tbody += '<td><input type="text" onclick="this.select();" class="pd-spec-prices" data-id="'
                                    + specs[i].data[j].id + '-'
                                    + specs[nex].data[j1].id + '" value="'
                                    + prices + '" /></td>';
                            tbody += '<td><input type="text" onclick="this.select();" class="pd-spec-market" data-id="'
                                    + specs[i].data[j].id + '-'
                                    + specs[nex].data[j1].id + '" value="0" /></td></tr>';
                        }
                    } else {
                        // 插入第一维数据
                        tbody += '<tr><td>' + specs[i].data[j].name + '</td>';
                        tbody += '<td>无</td>';
                        tbody += '<td><input type="text" onclick="this.select();" class="pd-spec-prices" data-id="'
                                + specs[i].data[j].id + '-'
                                + 0 + '" value="' + prices + '" /></td>';
                        tbody += '<td><input type="text" onclick="this.select();" class="pd-spec-market" data-id="'
                                + specs[i].data[j].id + '-'
                                + 0 + '" value="0" /></td></tr>';
                    }
                }
            }
        }
        thead += '<th>规格</th><th>规格</th><th>价格</th><th>市场参考价</th></tr></thead>';
        tbody += '</tbody>';
        $('#pd-spec-frame').html(thead + tbody).show();
    }

    fnFancyBox('#pd-spec-edit-btn-rep', function () {
        $('.fancybox-skin').css('padding', '0');

        $('#confirm_spec_btn').on('click', function () {
            var dets = [];
            dets.push({
                id: "",
                name: $('#pd-spec1-det-name').val(),
                sort: 0
            });
            // [httpPost]
            $.post(shoproot + '?/ProductSpec/ajaxAlterSpec/', {
                id: 0,
                dets: dets,
                spec_name: $('#pd-spec1-name').val(),
                spec_remark: '',
                append: true
            }, function (res) {
                if (res !== '0') {
                    var ids = res.split('-');
                    fnGenerateSpecTable([{
                            id: ids[0],
                            name: $('#pd-spec1-name').val(),
                            data: [{
                                    id: ids[1],
                                    name: $('#pd-spec1-det-name').val()
                                }]
                        }]);
                } else {
                    alert('提交失败！');
                }
                $.fancybox.close();
            });
        });

    });

    /**
     * 获取商品价格表
     * @returns {Array}
     */
    function getSpecs() {
        var spec = [];
        $('.pd-spec-prices').each(function () {
            spec.push({
                sid: $(this).attr('data-id'),
                price: parseFloat($(this).val()),
                market_price: parseFloat($(this).parent().parent().find('.pd-spec-market').val())
            });
        });
        return spec;
    }

});